import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('user', () => {
  const router = useRouter()
  
  // 从localStorage初始化状态
  const user = ref(JSON.parse(localStorage.getItem('user')) || {
    id: null,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    avatar: '',
    status: 0,
    roles: []
  })
  
  const token = ref(localStorage.getItem('token') || null)
  
  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value.roles?.includes('ROLE_ADMIN'))
  const userAvatar = computed(() => user.value.avatar || '/default-avatar.jpg')
  
  // 登录方法
  const login = async (username, password) => {
    try {
      const response = await axios.post('http://localhost:8080/api/auth/login', {
        username,
        password
      })
      
      token.value = response.data.token
      user.value = {
        id: response.data.id,
        username: response.data.username,
        nickname: response.data.nickname,
        email: response.data.email,
        phone: response.data.phone,
        avatar: response.data.avatar,
        status: response.data.status,
        roles: response.data.roles || []
      }
      
      // 持久化存储
      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))
      
      return true
    } catch (error) {
      console.error('登录错误详情:', error)
      ElMessage.error(error.response?.data?.message || '登录失败')
      return false
    }
  }
  
  // 登出方法
  const logout = () => {
    token.value = null
    user.value = {
      id: null,
      username: '',
      nickname: '',
      email: '',
      phone: '',
      avatar: '',
      status: 0,
      roles: []
    }
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
  }
  
  // 初始化用户信息
  const initUser = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      user.value = JSON.parse(savedUser)
    }
  }
  
  // 更新用户信息
  const updateUser = async (userInfo) => {
    try {
      const response = await axios.put(`/api/users/${user.value.id}`, userInfo, {
        headers: { Authorization: `Bearer ${token.value}` }
      })
      
      user.value = { ...user.value, ...response.data }
      localStorage.setItem('user', JSON.stringify(user.value))
      return true
    } catch (error) {
      ElMessage.error('更新用户信息失败')
      return false
    }
  }
  
  const register = async (userData) => {
    try {
      const response = await axios.post('http://localhost:8080/api/auth/register', userData)
      
      // 注册成功后可以自动登录，或者只返回成功消息
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('注册错误:', error)
      throw error
    }
  }
  return {
    user,
    token,
    isAuthenticated,
    isAdmin,
    userAvatar,
    login,
    logout,
    initUser,
    updateUser,
    register
  }
})